<script setup lang="ts">
  import { getLoginCodeApi } from '@/pages/apis/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  const form = ref<UniHelper.UniFormsInstance>()

  const isShowCountDown = ref(false)
  // 勾选用户协议
  const isAgree = ref(false)

  const formData = ref({
    mobile: '13230000020',
    password: '',
  })

  const formRules: UniHelper.UniFormsRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号' },
        { pattern: '^1[3-9]\\d{9}$', errorMessage: '请输入正确的手机号' },
      ],
    },
    password: {
      rules: [{ required: true, errorMessage: '请填写密码' }],
    },
  }

  // 登录
  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      if (!isAgree.value) {
        return (
          uni.showToast({
            title: '请勾选同意协议',
            icon: 'error',
          }),
          (isAgree.value = true)
        )
      }
      if (formData.value.password !== 'abc12345') {
        return uni.showToast({
          title: '密码错误',
          icon: 'error',
        })
      }
      const res = await getLoginCodeApi(formData.value)
      // console.log(res)
      const userStore = useUserStore()
      userStore.setToken(res.token)
      uni.showToast({ title: '登录成功' })
      uni.switchTab({ url: '/pages/index/index' })
    } catch (error) {
      console.log(error)
    }
  }
</script>
<template>
  <uni-forms class="login-form" ref="form" :rules="formRules" :model="formData">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="formData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit()">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
